// chat.js
const utils = require("../../utils/util.js")
const msgcon = require("./msgconfig");
const app = getApp();
const api = require("./../../api/api")
import Toast from "./../../miniprogram/miniprogram_npm/@vant/weapp/toast/toast"

const chatlist = [
  {
    id: -1,
    isright: false,
    showSendTime: true,
    type: 'text',
    sendTime: '2010/10/10 12:00',
    avatarimg: '/static/image/chat/extra.png',
    mgscontent: '有什么问题快像我提问吧！',
    voicelen: 5
  },
  {
    id: 2,
    isright: true,
    showSendTime: false,
    type: 'text',
    sendTime: '2010/10/10 12:00',
    avatarimg: '/static/image/chat/extra.png',
    mgscontent: '有什么问题快像我提问吧！',
    voicelen: 5
  },
  {
    id: 3,
    isright: false,
    showSendTime: false,
    type: 'img',
    sendTime: '2010/10/10 12:00',
    avatarimg: '/static/image/chat/extra.png',
    mgscontent: '有什么问题快像我提问吧！',
    imgsrc: "/static/5a6e0fcf44ec50f7.png",
    voicelen: 5
  }
];

Page({
  data: {
    toView: 0,
    chatLists: [],
    scrollTopTimeStamp: 0,
    height: 0,  //屏幕高度
    chatHeight: 0,//聊天屏幕高度

    normalDataTime: '',
    avatarUrl: '',
    tosb: '121212',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.initData();
    this.toViewBottom();
  },

  GetSocketConnection: function () {
    //建立连接
    wx.connectSocket({
      url: "ws://localhost:3000/ws",
    })

    //连接成功
    wx.onSocketOpen(function () {
      wx.sendSocketMessage({
        data: '微信发的消息',
      })
    })

    //接收数据
    wx.onSocketMessage(function (data) {
      console.log(data);

      let chats = that.data.chatLists;
      let msg = msgcon.creatTextMsg(chats.length, "/static/5a6e0fcf44ec50f7.png", data.data, false);

      chats.push(msg);
      that.setData({
        chatLists: chats
      })
      that.toViewBottom();
    })

    //连接失败
    wx.onSocketError(function () {
      console.log('websocket连接失败！');
    })

    wx.onSocketClose(function (res) {
      console.log('WebSocket 已关闭！')
    })
  },


  initData: function () {
    let that = this;
    //获取屏幕的高度
    wx.getSystemInfo({
      success(res) {
        that.setData({
          height: wx.getSystemInfoSync().windowHeight,
          chatHeight: wx.getSystemInfoSync().windowHeight - 55
        })
      }
    })
    that.setData({
      normalDataTime: utils.formatTime(new Date()),
      toView: that.data.chatLists.length,
      avatarUrl: wx.getStorageSync('avatarUrl')
    });
    wx.setNavigationBarTitle({
      title: '与XX聊天...'
    });
    that.toViewBottom();
  },


  // 发送文本信息
  sendMsg: async function (e) {
    console.log('文本信息发送', e.detail)
    let chats = this.data.chatLists;

    let msg = {
      userId: wx.getStorageSync('userId'),
      tosb: this.data.tosb,
      msgtype: 'text',
      content: e.detail,
    }

    try {
      let res = await api.post('/chat/sendtext', msg)
      console.log(res);
      if (res.data.code == 200) {
        console.log(res.data.sendTime)
        msg = this.createTextMsg(res.data.msgId, res.data.content, res.data.sendTime);
        chats.push(msg);
        this.setData({
          chatLists: chats
        })
        this.toViewBottom();
      } else {
        console.log('error');
        Toast('error');
      }
    } catch (error) {
      console.log(error);
      Toast('error');
    }
  },


  createTextMsg: function (id, content, sendTime) {
    return {
      id: id,
      isright: true,
      showSendTime: true,
      type: 'text',
      sendTime: sendTime,
      avatarimg: this.data.avatarUrl,
      mgscontent: content
    }
  },

  // 从相机或者相册选择照片
  chooseImg: function () {
    let that = this
    console.log('照片')
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths[0]
        console.log(tempFilePaths)
        let chats = that.data.chatLists;

        let msg = msgcon.createImgMsg(chats.length, '/static/5a6e0fcf44ec50f7.png', tempFilePaths);
        chats.push(msg);
        that.setData({
          chatLists: chats
        })
        that.toViewBottom();
      }
    })
  },


  // 设置屏幕自动滚动到最后一条消息处
  toViewBottom: function () {
    this.setData({
      toView: `item-${this.data.chatLists.length}`
    })
  },


  onPullDownRefresh: function () {
    console.log('上拉刷新')
  },
});
